package com.config;

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.json.jackson.JacksonJsonpMapper;
import co.elastic.clients.transport.ElasticsearchTransport;
import co.elastic.clients.transport.rest_client.RestClientTransport;
import nl.altindag.ssl.SSLFactory;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.elasticsearch.client.RestClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;
import java.util.LinkedList;
import java.util.List;

/**
 * @author xiaoshu
 */
@Configuration
public class ElasticSearchConfig {
    private ElasticSearchPropertie elasticSearchPropertie;

    @Autowired
    public ElasticSearchConfig(ElasticSearchPropertie elasticSearchPropertie) {
        this.elasticSearchPropertie = elasticSearchPropertie;
    }

    @Bean
    public ElasticsearchClient elasticsearchClient(){
        List<ElasticSearchPropertie.Node> nodes = elasticSearchPropertie.getNodes();
        List<HttpHost> httpHosts = new LinkedList<>();
        nodes.forEach(e->{
            HttpHost httpHost = new HttpHost(e.getIp(), e.getPort(), e.getScheme());
            httpHosts.add(httpHost);
        });

        final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY,
                new UsernamePasswordCredentials(elasticSearchPropertie.getUserName(), elasticSearchPropertie.getPassword()));

        SSLFactory sslFactory = SSLFactory.builder()
                .withUnsafeTrustMaterial()
                .withUnsafeHostnameVerifier()
                .build();
        HttpHost[] hosts = httpHosts.toArray(new HttpHost[]{});
        RestClient client = RestClient.builder(hosts)
                .setHttpClientConfigCallback(x ->
                        x.setDefaultCredentialsProvider(credentialsProvider)
                                .setSSLContext(sslFactory.getSslContext())
                                .setSSLHostnameVerifier(sslFactory.getHostnameVerifier())
                ).build();
        ElasticsearchTransport transport = new RestClientTransport(client,new JacksonJsonpMapper());
        return new ElasticsearchClient(transport);
    }


}
